from django.shortcuts import render
from rest_framework import viewsets, permissions, status

from Auth.models import User
from Auth.serializers import UserSerializer

from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response


# Create your views here.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class CustomAuthToken(ObtainAuthToken):
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        res_data = {
            'code': 200,
            'status': 'success',
            'message': '登录成功',
            'data': {
                'token': token.key,
                'user_id': user.pk,
                'is_admin': user.is_superuser,
                # 'email': user.email
            }
        }
        return Response(res_data, status=status.HTTP_200_OK)

